import {
  forwardRef,
  useState,
  useImperativeHandle,
  useRef,
  useEffect,
} from 'react'
import { Animated, StyleSheet, Text } from 'react-native'

interface LikeIconAttr {
  translateX: number
  translateY: number
  id: number
  rotateZ: number
}

export interface LikeIconWrapRef {
  pushList: (item: LikeIconAttr) => void
}
export default forwardRef(function (props: any, ref) {
  const [list, setList] = useState<LikeIconAttr[]>([])
  function onFinished(id: number) {
    setList(val => {
      return val.filter(item => item.id !== id)
    })
  }
  useImperativeHandle(
    ref,
    () => ({
      pushList(item: LikeIconAttr) {
        setList(val => {
          return val.concat(item)
        })
      },
    }),
    [],
  )
  return (
    <>
      {list.map(item => (
        <LikeIcon key={item.id} {...item} onFinished={onFinished} />
      ))}
    </>
  )
})
interface LikeIconProps extends LikeIconAttr {
  onFinished?: (id: number) => void
}
function LikeIcon(props: LikeIconProps) {
  const likeIconAnimated = useRef(new Animated.Value(0)).current // 喜欢图标的动画
  useEffect(() => {
    Animated.timing(likeIconAnimated, {
      toValue: 1,
      useNativeDriver: false,
      duration: 400,
    }).start(() => {
      setTimeout(() => {
        Animated.timing(likeIconAnimated, {
          toValue: 0,
          useNativeDriver: false,
          duration: 100,
        }).start(() => {
          props.onFinished && props.onFinished(props.id)
        })
      }, 300)
    })
  }, [])
  return (
    <Animated.View
      style={[
        style.videoLikeWrap,
        {
          transform: [
            { translateX: props.translateX },
            { translateY: props.translateY },
            { rotateZ: props.rotateZ + 'deg' },
            { scale: likeIconAnimated },
          ],
          opacity: likeIconAnimated,
        },
      ]}
    >
      <Text style={style.videoLike}>&#x1018e;</Text>
    </Animated.View>
  )
}

const style = StyleSheet.create({
  videoLikeWrap: {
    position: 'absolute',
    left: -40,
    top: -40,
    width: 80,
    height: 80,
    backgroundColor: '#ffffff66',
    borderRadius: 20,
  },
  videoLike: {
    fontFamily: 'iconfont',
    color: '#f392a6',
    fontSize: 80,
  },
  videoPressWrap: {
    zIndex: 2,
  },
  videoPlusIcon: {
    width: 80,
    height: 80,
    left: '50%',
    top: '50%',
    transform: [{ translateY: -40 }, { translateX: -40 }],
    position: 'absolute',
    borderRadius: 40,
    justifyContent: 'center',
  },
})
